import { createRouter, createWebHistory } from 'vue-router'
import PKIndexView from '@/views/pk/PKIndexView'
import RecordIndexView from '@/views/record/RecordIndexView'
import RecordContentView from '@/views/record/RecordContentView'
import RanklistIndexView from '@/views/ranklist/RanklistIndexView'
import UserBotIndexView from '@/views/user/bots/UserBotIndexView'
import NotFound from '@/views/error/NotFound'
import UserAccountLoginView from '@/views/user/account/UserAccountLoginView'
import UserAccountRegisterView from '@/views/user/account/UserAccountRegisterView'
import UserAccountAcWingReceiveCode from '@/views/user/account/UserAccountAcWingReceiveCode'
import store from '@/store/index'

const routes = [
    {
        path: '/',
        name: 'home',
        redirect: '/pk',
        meta: {
            requestAuth: true, // 是否需要授权
        },
    },
    {
        path: '/pk',
        name: 'pk_index',
        component: PKIndexView,
        meta: {
            requestAuth: true,
        },
    },
    {
        path: '/record',
        name: 'record_index',
        component: RecordIndexView,
        meta: {
            requestAuth: true,
        },
    },
    {
        path: '/record/:recordId',
        name: 'record_content',
        component: RecordContentView,
        meta: {
            requestAuth: true,
        },
    },
    {
        path: '/ranklist',
        name: 'ranklist_index',
        component: RanklistIndexView,
        meta: {
            requestAuth: false,
        },
    },
    {
        path: '/user/bot',
        name: 'user_bot_index',
        component: UserBotIndexView,
        meta: {
            requestAuth: true,
        },
    },
    {
        path: '/user/account/acwing/receive_code',  // 此处的路由名称必须和后端设置的回调前端路径一致
        name: 'user_account_acwing_receive_code',
        component: UserAccountAcWingReceiveCode,
        meta: {
            requestAuth: false,
        },
    },
    {
        path: '/user/account/login/',
        name: 'user_account_login',
        component: UserAccountLoginView,
        meta: {
            requestAuth: false,
        },
    },
    {
        path: '/user/account/register',
        name: 'user_account_register',
        component: UserAccountRegisterView,
        meta: {
            requestAuth: false,
        },
    },
    {
        path: '/404',
        name: '404',
        component: NotFound,
        meta: {
            requestAuth: false,
        },
    },
    {
        path: '/:catchAll(.*)',
        redirect: '/404',
    },
]

const router = createRouter({
    history: createWebHistory(),
    routes,
})

router.beforeEach((to, from, next) => {
    if (to.meta.requestAuth && !store.state.user.is_login) {
        next({ name: 'user_account_login' }) // 跳转到指定页面
    } else {
        next() // 跳转到默认页面即可
    }
})

export default router
